<!--
工单管理
 * @Author: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @Date: 2025-05-25 16:46:30
 * @LastEditors: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @LastEditTime: 2025-06-02 21:52:21
 * @FilePath: \nsk-ui\src\views\street\workManage\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="work">
    <div class="work-table">
      <el-form
        :model="searchForm"
        class="search-form"
        inline
        style="margin-bottom: 12px"
      >
        <el-form-item label="工单编号">
          <el-input
            v-model="searchForm.workOrderNumber"
            placeholder="请输入工单编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="工单来源">
          <el-select
            v-model="searchForm.source"
            placeholder="请选择工单来源"
            clearable
          >
            <el-option label="12345" value="12345" />
            <el-option label="公众号" value="公众号" />
            <!-- 可根据实际数据源动态生成选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="导入日期">
          <el-date-picker
            v-model="searchForm.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="请选择导入日期区间"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item class="search-btn-group" style="margin-right: 0">
          <div class="btn-group">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="primary" @click="handleIn">工单导入</el-button>
            <el-button type="primary" :loading="aiLoading" @click="handleAI"
              >AI分析</el-button
            >
            <el-button
              type="primary"
              :loading="exportLoading"
              @click="handleOut"
            >
              {{ exportLoading ? "导出中..." : "导出工单" }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <div v-loading="tableLoading">
        <el-table :data="tableData" stripe style="min-height: 300px">
          <!-- 工单来源 -->
          <el-table-column
            prop="source"
            label="工单来源"
            show-overflow-tooltip
          />
          <!-- 工单编号 -->
          <el-table-column
            prop="workOrderNumber"
            label="工单编号"
            show-overflow-tooltip
          />

          <el-table-column
            prop="complaintCategoryLevel1"
            label="诉求分类（一级）"
            show-overflow-tooltip
          />

          <!-- 工单主题 -->
          <el-table-column
            prop="workOrderSubject"
            label="工单主题"
            show-overflow-tooltip
          />

          <!-- 工单内容 -->
          <el-table-column
            prop="workOrderContent"
            label="工单内容"
            show-overflow-tooltip
          />

          <!-- 分配科室 -->
          <el-table-column
            prop="departmentName"
            label="分配科室"
            show-overflow-tooltip
          />
          <el-table-column
            prop="replyContent"
            label="回复建议"
            show-overflow-tooltip
          />
          <!-- 纪工委督办 -->
          <!-- <el-table-column prop="isIdc" label="纪工委督办" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.isIdc === "0" ? "是" : "否" }}</span>
            </template>
          </el-table-column> -->
          <!-- 导入日期 -->
          <el-table-column
            prop="createTime"
            label="导入日期"
            show-overflow-tooltip
          />

          <!-- 操作 -->
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleOptions(row, 'view')"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-count">总共 {{ total }} 个项目</span>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next, jumper, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 详情 -->
    <detail-drawer
      v-if="drawerVisible"
      v-model:visible="drawerVisible"
      :type="drawerType"
      :asset-data="currentAssetData"
    />

    <el-dialog
      v-model="importDialogVisible"
      title="导入工单"
      width="500px"
      :close-on-click-modal="false"
    >
      <template v-if="importStep === 1">
        <el-upload
          class="upload-demo"
          drag
          :action="uploadFileUrl"
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleFileChange"
          :on-success="handleSuccess"
          :on-error="handleError"
          :file-list="importFile ? [importFile] : []"
          accept=".xlsx,.csv"
          :headers="headers"
          ref="uploadRef"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">点击或拖文件到这里上传</div>
          <template #tip>
            <div class="el-upload__tip">支持扩展名：.xlsx, .csv</div>
          </template>
        </el-upload>
        <div style="text-align: right; margin-top: 20px">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="loading"
            :disabled="!importFile"
            @click="submitImport"
            >提交</el-button
          >
        </div>
      </template>
      <template v-else>
        <div style="margin-bottom: 20px">
          <div>数据文件：{{ importResult.fileName }}</div>
          <div>文件记录数：{{ importResult.fileCount }}条</div>
          <div>入库记录数：{{ importResult.importCount }}条</div>
        </div>
        <div style="text-align: right">
          <el-button type="primary" @click="importDialogVisible = false"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, defineAsyncComponent } from "vue";
import { ElMessage } from "element-plus";
import { getList, getInfo } from "@/api/workOrdersAI"; // 导入新的接口方法
import { getToken } from "@/utils/auth";
import { aiAnalysis, exportWorkOrders } from "./services";
import dayjs from "dayjs";

const DetailDrawer = defineAsyncComponent(() =>
  import("@/components/DetailDrawer.vue")
);

// 表格数据
const tableData = ref([]);
const total = ref(0);
const tableLoading = ref(false);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
// 抽屉控制
const drawerVisible = ref(false);
const drawerType = ref("");
const currentAssetData = ref(null);

// 控制导入模态框显示
const importDialogVisible = ref(false);
// 控制导入步骤（1-上传，2-结果）
const importStep = ref(1);
// 上传文件信息
const importFile = ref(null);
const loading = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref(baseUrl + "/nsk/workOrders/importData"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const uploadRef = ref(null);
// 导入结果
const importResult = reactive({
  fileName: "",
  fileCount: 0,
  importCount: 0,
});

const searchForm = reactive({
  workOrderNumber: "", // 工单编号
  source: "", // 工单来源
  createTimeRange: [], // 导入日期区间
  departmentName: "", // 分配科室
  replyContent: "", // 回复建议
});

const aiLoading = ref(false);
const exportLoading = ref(false);

const handleOptions = async (row, type) => {
  const res = await getInfo(row.id);
  console.log("获取工单详情", res);
  if (res.code !== 200) {
    ElMessage.error(res.msg || "获取工单详情失败");
    return;
  }
  drawerVisible.value = true;
  drawerType.value = type;
  currentAssetData.value = { ...res.data, ...row };
};

// 获取表格数据
const fetchTableData = async () => {
  tableLoading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    };
    if (params.createTimeRange && params.createTimeRange.length === 2) {
      params.params = {
        beginTime: dayjs(params.createTimeRange[0]).format(
          "YYYY-MM-DD 00:00:00"
        ),
        endTime: dayjs(params.createTimeRange[1]).format("YYYY-MM-DD 23:59:59"),
      };
      delete params.createTimeRange;
    }
    const res = await getList(params);
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (e) {
    // 可选：ElMessage.error('获取数据失败')
  } finally {
    tableLoading.value = false;
  }
};
const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};
const handleIn = () => {
  importDialogVisible.value = true;
  importStep.value = 1;
  importFile.value = null;
};
const handleAI = async () => {
  aiLoading.value = true;
  try {
    const res = await aiAnalysis();
    if (res.code === 200) {
      ElMessage.success("AI分析任务已启动");
      // 刷新列表数据
      fetchTableData();
    } else {
      ElMessage.error(res.msg || "AI分析失败");
    }
  } catch (error) {
    console.error("AI分析失败：", error);
    ElMessage.error("AI分析失败，请稍后重试");
  } finally {
    aiLoading.value = false;
  }
};
const handleOut = async () => {
  try {
    exportLoading.value = true;
    // 传递查询参数
    const params = { ...searchForm };
    if (params.createTimeRange && params.createTimeRange.length === 2) {
      params.beginTime = dayjs(params.createTimeRange[0]).format(
        "YYYY-MM-DD 00:00:00"
      );
      params.endTime = dayjs(params.createTimeRange[1]).format(
        "YYYY-MM-DD 23:59:59"
      );
      delete params.createTimeRange;
    }
    // 过滤分页参数
    delete params.pageNum;
    delete params.pageSize;

    // 过滤掉无值的参数
    const cleanParams = {};
    Object.keys(params).forEach((key) => {
      const value = params[key];
      if (
        value !== undefined &&
        value !== null &&
        value !== "" &&
        !(Array.isArray(value) && value.length === 0)
      ) {
        cleanParams[key] = value;
      }
    });

    // 调用原有的导出接口
    const res = await exportWorkOrders(cleanParams);

    // 创建blob对象
    const blob = new Blob([res], { type: "application/vnd.ms-excel" });

    // 创建下载链接
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);

    // 设置文件名，使用当前日期
    const date = new Date();
    const fileName = `工单数据_${date.getFullYear()}${String(
      date.getMonth() + 1
    ).padStart(2, "0")}${String(date.getDate()).padStart(2, "0")}.xlsx`;
    link.download = fileName;

    // 触发下载
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败：", error);
    ElMessage.error("导出失败，请稍后重试");
  } finally {
    exportLoading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};

// 文件选择
const handleFileChange = (file) => {
  importFile.value = file;
};

// 提交导入
const submitImport = async () => {
  loading.value = true;
  uploadRef.value.submit();

  // try {
  //   loading.value = true
  //
  //   // 调用封装后的导入接口
  //   importWorkOrder(importFile.value.raw).then(res => {
  //     if (res.data && res.data.code === 200) { // 假设后端返回的数据结构有 code 和 data 字段
  //       importResult.fileName = res.data.data.fileName || importFile.value.name;
  //       importResult.fileCount = res.data.data.fileCount || 0;
  //       importResult.importCount = res.data.data.importCount || 0;
  //       importStep.value = 2; // 进入结果步骤
  //     } else {
  //       ElMessage.error(res.data.msg || '导入失败');
  //     }
  //   }).catch(err => {
  //     console.error('导入文件失败：', err);
  //     ElMessage.error('导入失败，请稍后再试或检查网络连接');
  //     loading.value = false;
  //     return;
  //   }).finally(() => {
  //     loading.value = false
  //   });
  // } catch (error) {
  //   console.error('导入文件失败：', error);
  //   ElMessage.error('导入失败，请稍后再试或检查网络连接');
  // }
};
const handleSuccess = (res) => {
  console.log("上传成功", res.msg);
  if (res.code !== 200) {
    ElMessage.error(res.msg || "导入失败");
    return;
  } else {
    let str = res.msg;
    let textMatch = str.match(/恭喜您，(.*?)共\s*\d+\s*条/);
    let numMatch = str.match(/共\s*(\d+)\s*条/);
    let text = textMatch ? textMatch[1].trim() : null;
    importStep.value = 2; // 进入结果步骤
    importResult.fileName = importFile.value.name;
    importResult.fileCount = numMatch || 0;
    importResult.importCount = text || 0;
  }
  loading.value = false;
};
const handleError = (err) => {
  console.log("上传失败", err);
  loading.value = false;
};

const resetImportDialog = () => {
  importStep.value = 1;
  importFile.value = null;
};

onMounted(() => {
  fetchTableData();
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
.search-form {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 16px;
}
.search-form .el-form-item {
  margin-bottom: 0;
}
.btn-group {
  display: flex;
  gap: 12px;
}
</style>
